package com.bridgeintelligent.tag.user.mgmt.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.user.mgmt.entity.Result;
import com.bridgeintelligent.tag.user.mgmt.entity.UserCodes;
import com.bridgeintelligent.tag.user.mgmt.mapper.RoleMgmtMapper;
import com.bridgeintelligent.tag.user.mgmt.mapper.UserMgmtMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.*;
import com.bridgeintelligent.tag.user.mgmt.util.HttpClientUtil;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.PasswordHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.security.aes.AesUtils;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户服务层接口实现
 */

@Service
@Slf4j
public class UserMgmtServiceImpl implements UserMgmtService {

    @Autowired
    private UserMgmtMapper UserMgmtMapper;

    @Autowired
    private RoleMgmtMapper roleMgmtMapper;

    /**
     * 新增用户(用户名)
     *
     * @param username
     * @return
     */
    @Override
    public boolean addUser(String username) {
        String userid = IDGenerator.gen();
        User user = new User(userid, username);
        //默认有效
        user.setEfftctiveSymbol(UserCodes.EFFTCTIVE_SYMBOL_01);
        //操作时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setOperateTime(sdf.format(new Date()));
//        String password = PasswordHelper.encode("78e910d0dc00b9ef83802abf2bd03e0b");
//        System.out.println(password);
//        user.setPassword(password);
        int count = UserMgmtMapper.addUser(user);
        return count > 0;
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean addUser(User user) {
        //默认有效
        user.setEfftctiveSymbol(UserCodes.EFFTCTIVE_SYMBOL_01);
        //操作时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setOperateTime(sdf.format(new Date()));
        user.setPassword(PasswordHelper.encode(user.getPassword()));
        int count = UserMgmtMapper.addUser(user);
        return count > 0;
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public void deleteUserByUserId(String userId) {
        UserMgmtMapper.deleteUserByUserId(userId);
    }

    /**
     * 修改用户
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {
        //操作时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setOperateTime(sdf.format(new Date()));
        UserMgmtMapper.updateUser(user);
    }


    /**
     * 上传文件,批量添加用户
     *
     * @param usernameList
     */
    @Override
    public void addFile(List<String> usernameList) {
        if (usernameList != null) {

            for (String username : usernameList) {
                String userid = IDGenerator.gen();
                User user = new User(userid, username);
                //操作时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                user.setOperateTime(sdf.format(new Date()));
                //默认有效
                user.setEfftctiveSymbol(UserCodes.EFFTCTIVE_SYMBOL_01);
                UserMgmtMapper.addUser(user);
            }
        }
    }


    @Override
    public Result updatePassword(String userId, String oldPassword, String newPassword,String comfirePassword) {
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(comfirePassword)){
            return new Result(-1,"密码不能为空");
        }
        if (oldPassword.equals(newPassword) || oldPassword.equals(comfirePassword)){
            return new Result(-1,"新旧密码不能一样");
        }
        if (!newPassword.equals(comfirePassword)){
            return new Result(-1,"新密码和确认密码不一致");
        }
        try {
            userId = AesUtils.aesDecrypt(userId, AesUtils.AES_KEY);
            oldPassword = AesUtils.aesDecrypt(oldPassword, AesUtils.AES_KEY);
            newPassword = AesUtils.aesDecrypt(newPassword, AesUtils.AES_KEY);
        }catch (Exception e){
            return new Result(-1,"解密失败");
        }

        //校验密码强弱性
        Map<String, String> map = PasswordHelper.validPwd(newPassword);
        if ("false".equals(map.get("F"))){
            return new Result(-1,map.get("M"));
        }

        User user = UserMgmtMapper.findUserById(userId);
        if (!user.getPassword().equals(PasswordHelper.encode(oldPassword))){
            return new Result(-1,"密码错误");
        }
        user.setPassword(PasswordHelper.encode(newPassword));
        UserMgmtMapper.updatePassword(user);
        return new Result(0,"密码修改成功");
    }


    @Transactional
    @Override
    public Result synchUserInfo(String jsonStr) {

        UserModel model = JSONObject.parseObject(jsonStr, UserModel.class);
        if (model == null) {
            return new Result(-1, "操作失败");
        }
        User user = new User();
        user.setUserId(model.getYu_cstno());//用户ID
        user.setYuSid(model.getYu_ssoid());
        user.setUsername(model.getYu_cstno()); //工号
        user.setPassword("6cdcfb3b1ae42f8de6855cbc1a94eb17");//初始化密码clyjb@2019加密后的密文
        user.setName(model.getYu_cstname());//姓名
        user.setUserPhone(model.getYu_mobile());//手机号
        user.setOfficePhone(model.getYu_officephone());//办公电话
        user.setInstitution(model.getYu_company_id());//机构
        user.setDepartment(model.getYu_depart());//机构
        user.setOperateTime(DateHelper.currentDateTime());//操作时间
        if ("00".equals(model.getYu_state())) {
            user.setEfftctiveSymbol("01");//有效
        } else {
            user.setEfftctiveSymbol("02");//失效
        }
        user.setEmail(model.getYua_email());

        //根据用户ID判断用户是否存在
        User db = UserMgmtMapper.findUserByName(user.getUsername());
        if (db != null) {
            user.setPassword(db.getPassword());
            user.setUserId(db.getUserId());
            if (CollUtil.isEmpty(model.getRoleList())){
                user.setRoleId(db.getRoleId());
            }else{
                String roleStr = model.getRoleList().stream().collect(Collectors.joining(","));
                user.setRoleId(roleStr);
            }
            UserMgmtMapper.deleteUserByUserId(db.getUserId());
        }else{
            if (!CollUtil.isEmpty(model.getRoleList())){
                String roleStr = model.getRoleList().stream().collect(Collectors.joining(","));
                user.setRoleId(roleStr);
            }else{
                user.setRoleId("");
            }
        }
        UserMgmtMapper.addSynUser(user);

        return new Result(0, "操作成功");
    }

    @Override
    public Result findCustNoByIdCard(String card_id) {

        //获取请求地址
        String ccisUrl = roleMgmtMapper.ccisUrl();
        String realUrl = "http://"+ccisUrl.split("/")[2]+"/ccrp-customer-indicators/unified/query/getCreditCustInfo";
        log.info("请求身份证号查询客户号服务："+realUrl);
        //组装查询参数
        BusinessParams businessParams = new BusinessParams()
                .setQueryKey("DP004")
                .setIdNo(card_id);
        User user = TagSecurityHelper.currentUser();
        QueryModel model = new QueryModel()
                .setUserNo(user.getUserId())
                .setUserName(user.getUsername())
                .setSysName("CBMRS")
                .setParams(businessParams);
        String response = HttpClientUtil.doPostJson(realUrl, JSON.toJSONString(model));
        log.info("响应身份证号查询客户号服务：{}",response);
        if (StringUtils.isEmpty(response)){
            return new Result(-1,"查询身份证信息失败");
        }
        QueryResult queryResult = JSONObject.parseObject(response, QueryResult.class);
        if (queryResult == null){
            return new Result(-1,"查询失败");
        }else{
            if ("DPR0000".equals(queryResult.getRespCode())){
                return new Result(0,"查询成功",queryResult.getDatas().get("custId"));
            }else{
                return new Result(-1,queryResult.getRespMsg());
            }
        }
    }

    @Override
    public String getDataUrl(String type) {
        return UserMgmtMapper.dataBaseUrl(type);
    }

    public boolean checkName(User user){
        boolean flag = false;
        User u = UserMgmtMapper.findUserByName(user.getUsername());
        if (u == null){
            flag = true;
        }else{
            if (u.getUserId().equals(user.getUserId())){
                flag = true;
            }
        }
        return flag;

    }

    @Override
    public Result getDataToken() {
        User user = TagSecurityHelper.currentUser();
        //根据当前人的userId获取访问令牌token
        String tokenUrl = this.getDataUrl("ccis.token");
        Map<String,String> param = new HashMap<>();
        param.put("empno",user.getUserId());
        String resultStr = HttpClientUtil.doGet(tokenUrl, param);
        log.info("获取token请求url:{},响应结果：{}",tokenUrl,resultStr);
        if (StrUtil.isNotBlank(resultStr)){
            CcisModel ccisModel = JSONUtil.toBean(resultStr, CcisModel.class);
            if (ccisModel != null && ccisModel.getResp_code() == 0){
                String token = ccisModel.getDatas();
                String loginUrl = this.getDataUrl("ccis.login");
                loginUrl = loginUrl.replace("PARAM",token);
                loginUrl = loginUrl+"&systemName=CBMRS";
                log.info("loginUrl:{}",loginUrl);
                return new Result(0,"获取令牌成功",loginUrl);
            }else{
                return new Result(-1,"获取令牌失败"+ccisModel.getResp_msg());
            }
        }else{
            return new Result(-1,"获取令牌失败，请检查用户信息");
        }
    }
}
